package cn.ug.analyse.web.controller;

import cn.ug.analyse.mapper.entity.TerminalStatisticsEntity;
import cn.ug.analyse.mapper.entity.TerminalStatisticsResponseEntity;
import cn.ug.analyse.service.TerminalStatisticsService;
import cn.ug.bean.base.DataOtherTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.util.DateUtil;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 终端统计
 *  @author lvkk
 *  @date 2019/10/21.
 */
@RestController
@RequestMapping("/terminal")
public class TerminalStatisticsController {
    @Autowired
    private TerminalStatisticsService terminalStatisticsService;

    /**
     * app端-增加启动次数
     * @return
     */
    @RequestMapping(value = "/addLaunchTimes",method = RequestMethod.GET)
    public SerializeObject addLaunchTimes(@RequestHeader String model,@RequestHeader String app,@RequestHeader String os){
        TerminalStatisticsEntity entity = new TerminalStatisticsEntity();
        entity.setAppSystem(os);
        entity.setPhoneModel(model);
        entity.setAppVersion(app);
        entity.setLaunchDate(DateUtil.format(new Date(),"yyyy-MM-dd"));
        return terminalStatisticsService.addLaunchTimes(entity);
    }

    /**
     * 用户终端统计
     * @param accessToken
     * @param order
     * @param pageNum
     * @param pageSize
     * @param tabId
     * @param startDate
     * @param endDate
     * @param system
     * @return
     */
    @GetMapping(value = "/launchTimes/list")
    public SerializeObject findLaunchTimes(@RequestHeader String accessToken, Order order, Integer pageNum, Integer pageSize, Integer tabId, String startDate, String endDate, String system){
        //tabId: 1.系统版本，2.设备型号，3.app版本
        tabId = tabId == null ? 2 : tabId;
        if (tabId < 1 || tabId > 3) {
            return new SerializeObject<>(ResultType.ERROR, "tabId传参错误");
        }
        if (null == pageNum || pageNum <= 0){
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        SerializeObject data = terminalStatisticsService.findLaunchStatistics(tabId,startDate,endDate,system);
        List<TerminalStatisticsResponseEntity> list = (List<TerminalStatisticsResponseEntity>) data.getData();

        if (StringUtils.isNotBlank(order.getOrder()) && order.getOrder().contains(",")){
            order.setOrder(order.getOrder().replaceAll(",",""));
            order.setSort(order.getSort().replaceAll(",",""));
        }
        //排序，默认
        if (StringUtils.isBlank(order.getOrder())) {
            if (tabId == 1) {
                order.setOrder("appSystem");
            }
            if (tabId == 2) {
                order.setOrder("phoneModel");
            }
            if (tabId == 3) {
                order.setOrder("appVersion");
            }
            order.setSort("desc");
        }

        if (order.getOrder().equalsIgnoreCase("launchTimes")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getLaunchTimes));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getLaunchTimes).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("appSystem")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppSystem));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppSystem).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("phoneModel")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getPhoneModel));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getPhoneModel).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("appVersion")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppVersion));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppVersion).reversed());
            }
        }

        if (!CollectionUtils.isEmpty(list)) {
            Map map = new HashMap();
            Integer totalTimes = 0;

            for (TerminalStatisticsResponseEntity entity : list) {
                if (entity.getLaunchTimes() != null) {
                    totalTimes = totalTimes + entity.getLaunchTimes();
                }
            }

            map.put("totalTimes",totalTimes);
            int total = list.size();

            if (pageSize > 0) {
                list = list.stream().skip((PaginationUtil.getPage(pageNum) - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataOtherTable<TerminalStatisticsResponseEntity>(pageNum, pageSize, total, list,map));
        }

        return new SerializeObject<>(ResultType.NORMAL, new DataOtherTable<TerminalStatisticsResponseEntity>(pageNum, pageSize, 0, new ArrayList<TerminalStatisticsResponseEntity>(),new HashMap<>()));
    }

    /**
     * 用户终端统计导出
     * @param response
     * @param order
     * @param tabId
     * @param startDate
     * @param endDate
     * @param system
     */
    @GetMapping(value = "/launchTimes/export")
    public void exportLaunchTimes(HttpServletResponse response, Order order, Integer tabId, String startDate, String endDate, String system){
        //tabId: 1.系统版本，2.设备型号，3.app版本
        tabId = tabId == null ? 2 : tabId;
        if (tabId < 1 || tabId > 3) {
            return;
        }

        SerializeObject data = terminalStatisticsService.findLaunchStatistics(tabId,startDate,endDate,system);
        List<TerminalStatisticsResponseEntity> list = (List<TerminalStatisticsResponseEntity>) data.getData();

        if (StringUtils.isNotBlank(order.getOrder()) && order.getOrder().contains(",")){
            order.setOrder(order.getOrder().replaceAll(",",""));
            order.setSort(order.getSort().replaceAll(",",""));
        }
        //排序，默认
        if (StringUtils.isBlank(order.getOrder())) {
            if (tabId == 1) {
                order.setOrder("appSystem");
            }
            if (tabId == 2) {
                order.setOrder("phoneModel");
            }
            if (tabId == 3) {
                order.setOrder("appVersion");
            }
            order.setSort("desc");
        }

        if (order.getOrder().equalsIgnoreCase("launchTimes")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getLaunchTimes));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getLaunchTimes).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("appSystem")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppSystem));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppSystem).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("phoneModel")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getPhoneModel));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getPhoneModel).reversed());
            }
        }
        if (order.getOrder().equalsIgnoreCase("appVersion")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppVersion));
            } else {
                Collections.sort(list, Comparator.comparing(TerminalStatisticsResponseEntity::getAppVersion).reversed());
            }
        }

        ExportExcelController<TerminalStatisticsResponseEntity> export = new ExportExcelController<TerminalStatisticsResponseEntity>();
        String firstCloum = "";
        String cloumValue = "";
        if (tabId == 1) {
            firstCloum = "系统版本";
            cloumValue = "appSystem";
        }
        if (tabId == 2) {
            firstCloum = "设备型号";
            cloumValue = "phoneModel";
        }
        if (tabId == 3) {
            firstCloum = "APP版本";
            cloumValue = "appVersion";
        }
        String[] columnNames = {firstCloum, "启动次数（次）"};
        String[] columns = {cloumValue, "launchTimes"};
        String fileName = "用户终端统计";
        String[] firstLines = {"合计", "0"};

        if (!CollectionUtils.isEmpty(list)) {
            Map map = new HashMap();
            Integer totalTimes = 0;

            for (TerminalStatisticsResponseEntity entity : list) {
                if (entity.getLaunchTimes() != null) {
                    totalTimes = totalTimes + entity.getLaunchTimes();
                }
            }
            map.put("totalTimes",totalTimes);
            int total = list.size();
            String[] firstLines1 = {"合计", totalTimes + ""};

            export.exportUnlikeExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003, firstLines1);
        }
        export.exportUnlikeExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003, firstLines);

    }


}
